#include "tools.h"

//输入指令
char get_cmd(char start,char end)
{
	assert(start<=end);
	puts("--------------------");
	printf("请输入指令：");
	for(;;)
	{
		char cmd=getch();
		if(start<=cmd && cmd<=end)
		{
			printf("%c\n",cmd);
			return cmd;
		}
	}
}

//延时显示
void print_sec(const char* msg,float sec)
{
	printf("\33[01;32m %s \33[00m\n",msg);
	usleep(1000000*sec);
}

//输入字符串
char* get_str(char* str,size_t size)
{
	assert(NULL!=str && size>1);
	size_t len=strlen(fgets(str,size,stdin));
	if('\n'==str[len-1])
		str[len-1]='\0';
	else
		while('\n'!=getchar());
	return str;
}

//输入密码并隐藏
char* get_passwd(char* passwd,size_t size)
{
	int i=0;
	while(i<size-1)
	{
		passwd[i]=getch();
		if(127==passwd[i])
		{
			if(i>0)
			{
				i--;
				printf("\b \b");
			}
			continue;
		}
                else if(10 == passwd[i] || 32 == passwd[i])
		{
			continue;
		}
		i++;
		printf("*");
	}
	passwd[size-1]='\0';
	printf("\n");
	return passwd;
}
  
//输入手机号并限制位数
char* get_phone(char* phone,size_t size)
{
	int i=0;
	while(i<size-1)
	{
		phone[i]=getch();
		if(127==phone[i])
		{
			if(i>0)
			{
				i--;
				printf("\b \b");
			}
			continue;
		}
		else if(10 == phone[i] || 32 == phone[i])
		{
			continue;
		}
		else
		{
			i++;
			printf("%d",phone[i-1]-48);
		}
	}
	phone[size-1]='\0';
	printf("\n");
	return phone;
}

//按任意键继续
void anykey_continue(void)
{
	stdin -> _IO_read_ptr = stdin -> _IO_read_end;
	puts("按任意键继续...");
	getch();
}

//是否确认操作
bool yes_or_no(void)
{
	printf("是否确认此操作（y/n）?");
	for(;;)
	{
		char cmd=getch();
		if('y'==cmd || 'Y'==cmd || 'n'==cmd || 'N'==cmd)
		{
			printf("%c\n",cmd);
			return 'y'==cmd || 'Y'==cmd;
		}
	}
}

//通用的二进制保存数据
int save_data(void* base,size_t size,const char* path)
{
	assert(NULL!=base && 0!=size && NULL!=path);
	FILE* wfp=fopen(path,"w");
	if(NULL==wfp)
	{
		printf("文件打开失败，无法保存数据！\n");
		return -1;
	}
	int ret=fwrite(base,1,size,wfp);
	fclose(wfp);
	return ret;
}

//通用的二进制加载数据
int load_data(void* base,size_t size,const char* path)
{
	assert(NULL!=base && 0!=size && NULL!=path);
	FILE* rfp=fopen(path,"r");
	if(NULL==rfp)
	{
		printf("文件打开失败，加载数据失败！\n");
		return 0;
	}
	int ret=fread(base,1,size,rfp);
	fclose(rfp);
	return ret;
}
